package com.demo.order.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置类
 * 配置订单服务的消息队列
 */
@Configuration
public class RabbitMQConfig {

    // 秒杀交换机
    public static final String SECKILL_EXCHANGE = "seckill.exchange";
    
    // 秒杀队列
    public static final String SECKILL_QUEUE = "seckill.queue";
    
    // 秒杀路由键
    public static final String SECKILL_ROUTING_KEY = "seckill.order";
    
    // 死信交换机
    public static final String SECKILL_DLX_EXCHANGE = "seckill.dlx.exchange";
    
    // 死信队列
    public static final String SECKILL_DLX_QUEUE = "seckill.dlx.queue";
    
    // 死信路由键
    public static final String SECKILL_DLX_ROUTING_KEY = "seckill.dlx";

    /**
     * 创建秒杀交换机
     * @return DirectExchange
     */
    @Bean
    public DirectExchange seckillExchange() {
        return new DirectExchange(SECKILL_EXCHANGE, true, false);
    }

    /**
     * 创建秒杀队列
     * @return Queue
     */
    @Bean
    public Queue seckillQueue() {
        return QueueBuilder.durable(SECKILL_QUEUE)
                .withArgument("x-dead-letter-exchange", SECKILL_DLX_EXCHANGE)
                .withArgument("x-dead-letter-routing-key", SECKILL_DLX_ROUTING_KEY)
                .withArgument("x-message-ttl", 1800000) // 30分钟TTL
                .build();
    }

    /**
     * 绑定秒杀队列到交换机
     * @return Binding
     */
    @Bean
    public Binding seckillBinding() {
        return BindingBuilder.bind(seckillQueue())
                .to(seckillExchange())
                .with(SECKILL_ROUTING_KEY);
    }

    /**
     * 创建死信交换机
     * @return DirectExchange
     */
    @Bean
    public DirectExchange seckillDlxExchange() {
        return new DirectExchange(SECKILL_DLX_EXCHANGE, true, false);
    }

    /**
     * 创建死信队列
     * @return Queue
     */
    @Bean
    public Queue seckillDlxQueue() {
        return QueueBuilder.durable(SECKILL_DLX_QUEUE).build();
    }

    /**
     * 绑定死信队列到死信交换机
     * @return Binding
     */
    @Bean
    public Binding seckillDlxBinding() {
        return BindingBuilder.bind(seckillDlxQueue())
                .to(seckillDlxExchange())
                .with(SECKILL_DLX_ROUTING_KEY);
    }
}